<template>
  <div class="container" >
	<!--工具栏-->
	<div class="toolbar" style="float:left;padding-top:10px;padding-left:15px;">
		<el-form :inline="true" :model="filters" :size="size">

			<el-form-item label="学期" prop="termId">
				 <el-select v-model="filters.termId" placeholder="请选择" clearable>
            <el-option
              v-for="item in termOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
			</el-form-item>
			<el-form-item label="科目类型" prop="subjectType" >
				 <el-select v-model="filters.subjectType" placeholder="请选择" clearable>
            <el-option
              v-for="item in subjectOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
			</el-form-item>
      			<el-form-item  label="名称编码" prop="subjectName" >
				<el-input v-model="filters.subjectName" placeholder="名称" clearable></el-input>
			</el-form-item>
			<el-form-item>
				<kt-button :label="$t('action.search')" perms="sys:busSubject:view" type="primary" @click="findPage(null)"/>
			</el-form-item>
			<el-form-item>
				<kt-button :label="$t('action.add')" perms="sys:busSubject:add" type="primary" @click="handleAdd" />
			</el-form-item>
		</el-form>
	</div>
	<!--表格内容栏-->
	<kt-table permsEdit="sys:busSubject:edit" permsDelete="sys:busSubject:delete"
		:data="pageResult" :columns="columns"
		@findPage="findPage" @handleEdit="handleEdit" @handleDelete="handleDelete">
	</kt-table>
	<!--新增编辑界面-->
	<el-dialog :title="operation?'新增':'编辑'" width="40%" :visible.sync="editDialogVisible" :close-on-click-modal="false">
		<el-form :model="dataForm" label-width="80px" :rules="dataFormRules" ref="dataForm" :size="size">
			<el-form-item label="学期id" prop="termId"   >
			    <el-select v-model="dataForm.termId" placeholder="请选择" style="width: 100%;">
            <el-option
              v-for="item in termOptionsSave"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
			</el-form-item>
      	<el-form-item label="科目类型" prop="subjectType"   >
        	<el-select v-model="dataForm.subjectType" placeholder="请选择" style="width: 100%;">
            <el-option
              v-for="item in subjectOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
			</el-form-item>
			<el-form-item label="科目名称" prop="subjectName"   >
				<el-input v-model="dataForm.subjectName" auto-complete="off"></el-input>
			</el-form-item>
			<el-form-item label="科目编码" prop="subjectCode"   >
				<el-input v-model="dataForm.subjectCode" auto-complete="off"></el-input>
			</el-form-item>
			<el-form-item label="科目学分" prop="subjectCredit"   >
				<el-input v-model="dataForm.subjectCredit" auto-complete="off"></el-input>
			</el-form-item>

			<el-form-item label="学生" prop="students"  v-if="!operation" >
        <el-tree :data="studentData" size="mini" show-checkbox  node-key="id" :props="deptTreeProps"
          style="width: 100%;pading-top:20px;" ref="deptTree"
         >
        </el-tree>
			</el-form-item>

    </el-form>
		<div slot="footer" class="dialog-footer">
			<el-button :size="size" @click.native="editDialogVisible = false">{{$t('action.cancel')}}</el-button>
			<el-button :size="size" type="primary" @click.native="submitForm" :loading="editLoading">{{$t('action.submit')}}</el-button>
		</div>
	</el-dialog>
  </div>
</template>

<script>
import KtTable from "@/views/Core/KtTable"
import KtButton from "@/views/Core/KtButton"
import { format } from "@/utils/datetime"
export default {
	components:{
			KtTable,
			KtButton
	},
	data() {
		return {
			size: 'small',
			filters: {
				subjectName: '',
        termId:'',
        subjectType:''
			},
			columns: [
				{prop:"termName", label:"学期id", minWidth:100},
				{prop:"subjectName", label:"科目名称", minWidth:100},
				{prop:"subjectCode", label:"科目编码", minWidth:100},
				{prop:"subjectCredit", label:"科目学分", minWidth:100},
				{prop:"subjectType", label:"科目类型", minWidth:100,formatter: this.typeFormat},
				{prop:"createBy", label:"创建人", minWidth:100},
				{prop:"createTime", label:"创建时间", minWidth:100,formatter: this.dateFormat},
			],
			pageRequest: { pageNum: 1, pageSize: 8 },
			pageResult: {},

			operation: false, // true:新增, false:编辑
			editDialogVisible: false, // 新增编辑界面是否显示
			editLoading: false,
			dataFormRules: {
				label: [
					{ required: true, message: '请输入名称', trigger: 'blur' }
				]
			},
			// 新增编辑界面数据
			dataForm: {
				id: null,
				termId: null,
				subjectName: null,
				subjectCode: null,
				subjectCredit: null,
				subjectType: null,
        userSubjectList:[],
			},
      termOptions:[],
      termOptionsSave:[],
      subjectOptions:[
        {id:1,name:'智育'},
        {id:2,name:'体育'}
      ],
      values:[],
      studentData:[],
      deptTreeProps: {
				label: 'name',
				children: 'children'
			},
		}
	},
	methods: {
		// 获取分页数据
		findPage: function (data) {
			if(data !== null) {
				this.pageRequest = data.pageRequest
			}
      this.pageRequest.params = [{name:'subjectName', value:this.filters.subjectName},{name:'subjectType', value:this.filters.subjectType},{name:'termId', value:this.filters.termId}]
			this.$api.busSubject.findPage(this.pageRequest).then((res) => {
				this.pageResult = res.data
			}).then(data!=null?data.callback:'')
		},
		// 批量删除
		handleDelete: function (data) {
			this.$api.busSubject.batchDelete(data.params).then(data!=null?data.callback:'')
		},
		// 显示新增界面
		handleAdd: function () {
			this.editDialogVisible = true
			this.operation = true
			this.dataForm = {
				id: null,
				termId: null,
				subjectName: null,
				subjectCode: null,
				subjectCredit: null,
				subjectType: null,
        userSubjectList:[],
			}
		},
		// 显示编辑界面
		handleEdit: function (params) {
			this.editDialogVisible = true
			this.operation = false
			this.dataForm = Object.assign({}, params.row)
      this.$api.busSubject.findUsersBySubject(params.row.id).then(res =>{
        	this.$refs.deptTree.setCheckedNodes(res.data)
      })
		},
		// 编辑
		submitForm: function () {
			this.$refs.dataForm.validate((valid) => {
				if (valid) {
					this.$confirm('确认提交吗？', '提示', {}).then(() => {
						this.editLoading = true
            if(!this.operation){
              let checkedNodes = this.$refs.deptTree.getCheckedNodes(true, true)
              let userSubjects = []
              for(let i=0, len=checkedNodes.length; i<len; i++) {
                if(checkedNodes[i].type == 8){
                let userSubject = { userId:Math.abs(checkedNodes[i].id), subjectId:this.dataForm.id}
                 userSubjects.push(userSubject)
                }
              }
              this.dataForm.userSubjectList = userSubjects
            }
						let params = Object.assign({}, this.dataForm)
						this.$api.busSubject.save(params).then((res) => {
							if(res.code == 200) {
								this.$message({ message: '操作成功', type: 'success' })
                if(!this.operation){
                  this.$refs.deptTree.setCheckedNodes([])
                }
							} else {
								this.$message({message: '操作失败, ' + res.msg, type: 'error'})
							}
							this.editLoading = false
							this.$refs['dataForm'].resetFields()
							this.editDialogVisible = false
							this.findPage(null)
						})
					})
				}
			})
		},
      getTermOptions: function (type){
        this.$api.busTerm.findOptions(type).then(res  =>{
          if(type == 0){
            this.termOptions = res.data
          }else{
              this.termOptionsSave = res.data
          }
        })
      },
		// 时间格式化
      dateFormat: function (row, column, cellValue, index){
        return format(row[column.property])
      },
		// 状态格式化
  typeFormat: function (row, column, cellValue, index){
        if(row.subjectType == 1){
          return "智育"
        }else if(row.subjectType == 2){
          return "体育"
        }
	  },
		// 获取部门列表
		findDeptTree: function () {
			this.$api.dept.findStudentTree().then((res) => {
				this.studentData = res.data
			})
		},

  },
	mounted() {
    this.getTermOptions(0)
    this.getTermOptions(1)
    this.findDeptTree()
	}
}
</script>

<style scoped>

</style>
